<template>
  <div class="map-container">
    <div id="overlays"></div>
  </div>
</template>

<script setup>
  import Map from 'ol/Map';
  import Overlay from 'ol/Overlay';
  import TileLayer from 'ol/layer/Tile';
  import View from 'ol/View';
  import { fromLonLat } from "ol/proj";
  import XYZ from 'ol/source/XYZ';
  import { onMounted, ref } from "vue";

  let map = null;
  const imgUrl = new URL('../assets/vue.svg', import.meta.url).href;
  const pointData = ref([
    {
      title: '南京',
      position: [118.801847,32.062449]
    },
    {
      title: '合肥',
      position: [117.232866,31.82486]
    }
  ]);
  // var coordinate = ol.extent.getCenter(feature.getGeometry().getExtent());
  onMounted(() => {
    // 初始化地图
    map = new Map({
      target: 'overlays',
      layers: [
        new TileLayer({
          source: new XYZ({
           url: 'http://t0.tianditu.com/DataServer?T=img_w&X={x}&Y={y}&L={z}&tk=d3322c0d714d386b3bc91e3d24f37390'
          })
        }),
      ],
      view: new View({
        center: fromLonLat([118.802709, 32.065386]),
        zoom: 6,
        maxZoom: 12,
      })
    })
    // 这里利用现有坐标点生成overlay
    pointData.value.forEach((item, index) => {
      // 遍历时为元素添加id属性
      const div = document.createElement('div');
      div.setAttribute('class', 'pop');
      div.setAttribute('id', `${index}`);
      div.innerHTML = `
        <img class="img" src="${imgUrl}" alt="img">
        <span class="title">${item.title}</span>
      `;
      div.onclick = function(e) {
        console.log(this.getAttribute('id'));
      };
      div.onmouseover= function() {
        div.style.scale = 1.3;
      }
      div.onmouseout = function() {
        div.style.scale = 1;
      }
      let overlay = new Overlay({
        element: div
      })
      overlay.setPosition(fromLonLat(item.position));
      map.addOverlay(overlay);
    })
  })
</script>

<style lang="less" scoped>
  .map-container {
    position: relative;
    #overlays {
      width: 100vw;
      height: 100vh;
      position: absolute;
      left: 0;
      top: 0;
      /deep/ .pop {
        width: 30px;
        height: 30px;
        text-align: center;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: transparent;
        .img {
          width: 16px;
          height: 16px;
        }
        .title {
          font-size: 12px;
          color: red;
        }
      }
    }
  }
</style>